import { ExtensionContext, workspace, window } from 'vscode';
import * as fs from "fs";
import axios from 'axios';
import { ConfigUtil, EConfig, ICatchDetailConfig } from './lib/config';
import path = require('path');
import { IChapter } from './lib/RequestUtil';

export class Book {
    currPageNumber: number = 1;
    pageSize: number = 50;
    pageCount = 0;
    filePath: string | undefined = "";
    fileContent: string = '';

    constructor(public extensionPath: string) {
        this.init();
        this.bookContentInit();
    }

    public setNewBookStatus(bookPath: string) {
        if (!fs.existsSync(bookPath)) {
            window.showErrorMessage('End book file');
            return;
        }
        this.filePath = bookPath;
        this.currPageNumber = 1;

        ConfigUtil.setCurPageNumber(this.currPageNumber);
        ConfigUtil.setFilePath(this.filePath);

        this.readFile(bookPath);

        window.setStatusBarMessage(this.getCurPageContent());
    }

    private bookContentInit() {
        this.bookFix();
    }

    private bookFix() {
    }

    getSize(text: string): number {
        let size = text.length;
        this.pageCount = Math.ceil(size / this.pageSize!);
        return this.pageCount;
    }

    getFileName() {
        var fileName: string | undefined = this.filePath!.split("/").pop();
        console.log(fileName);
    }

    setCurPageNumber(type: EPageDirection, pageNumber?: number): void {
        if (type === EPageDirection.previous) {
            this.currPageNumber--;
        } else if (type === EPageDirection.next) {
            this.currPageNumber++;
        } else if (type === EPageDirection.cur) {
            this.currPageNumber = pageNumber!;
        }

        this.currPageNumber = Math.min(this.pageCount, this.currPageNumber);
        this.currPageNumber = Math.max(1, this.currPageNumber);

        this.updatePage();
    }

    updatePage() {
        ConfigUtil.setCurPageNumber(this.currPageNumber);
    }

    readFile(filePath: string) {
        if (!filePath) {
            return;
        }
        if (!fs.existsSync(filePath)) {
            window.showErrorMessage(`file: ${filePath} \n Not exists`);
            return;
        }

        let str = fs.readFileSync(filePath, { encoding: 'utf-8' });
        str = str.toString().replace(/\n/g, " ").replace(/\r/g, " ").replace(/　　/g, " ").replace(/ /g, " ");

        this.fileContent = str.toString().replace(/\n/g, " ").replace(/\r/g, " ").replace(/　　/g, " ").replace(/ /g, " ");
        this.filePath = filePath;
        this.pageCount = this.getSize(this.fileContent);
    }

    init() {
        this.currPageNumber = ConfigUtil.getCurPageNumber();
        this.pageSize = ConfigUtil.getPageSize();

        this.readFile(ConfigUtil.getFilePath());
    }

    getPreviousPage() {
        this.setCurPageNumber(EPageDirection.previous);
        return this.getCurPageContent();
    }

    getNextPage() {
        if (this.currPageNumber < this.pageCount) {
            this.setCurPageNumber(EPageDirection.next);
            return this.getCurPageContent();
        } else {
            // next book chapter
            let dir = path.dirname(this.filePath!);
            let curSortId = this.getFileSortId();
            let nextFilePath = `${dir}/${curSortId + 1}.txt`;
            this.setNewBookStatus(nextFilePath);
            return this.getCurPageContent();
        }
    }

    private getFileSortId() {
        let fileName = path.basename(this.filePath!);
        let curSortId = parseInt(fileName.replace('.txt', ''));
        return curSortId;
    }

    getJumpingPage(curPageNumber: number) {
        this.setCurPageNumber(EPageDirection.cur, curPageNumber);
        return this.getCurPageContent();
    }

    getCurPageContent(): string {
        let pageInfo = `${this.currPageNumber}/${this.pageCount}`;
        let startIndex = this.currPageNumber * this.pageSize - this.pageSize;
        let content = this.fileContent.substring(startIndex, startIndex + this.pageSize);
        return `${content} ${pageInfo}`;
    }

    getCurBookInfo(): string {
        let curSortId = this.getFileSortId();
        let bookInfo = '';
        let bookDir = path.resolve(this.filePath!, '../', '../');
        let bookName = path.basename(bookDir);
        let chapters: IChapter[] = JSON.parse(fs.readFileSync(`${bookDir}/data.json`, { encoding: 'utf-8' }));
        let curChapter = chapters.find(a => a.sortId === curSortId);
        bookInfo = `【${bookName}】[${curSortId}] ${curChapter?.title} ${this.currPageNumber}/${this.pageCount}`;
        return bookInfo;
    }
}

enum EPageDirection {
    previous,
    next,
    cur
}
